//
//  SHCountDownView.swift
//  SHCountDown
//
//  Created by jiaxing liu on 2019/1/25.
//  Copyright © 2019 jiaxing liu. All rights reserved.
//

import UIKit

class SHCountDownView: UIView {
    // MARK - 定时器
    fileprivate var timer:DispatchSourceTimer?
    // MARK - 是否启动定时器
    var isStartTimer = true
    
    // MARK - 结束时间
    open var endTime:Double? {
        didSet {
            if isStartTimer == true {
                if timer != nil { return }
                
                let queue = DispatchQueue.global()
                timer     = DispatchSource.makeTimerSource( queue: queue)
                timer?.schedule(wallDeadline: .now(),repeating: .seconds(1))
                timer?.setEventHandler { [weak self] in
                    DispatchQueue.main.async(execute: {
                        self?.refreshTime()
                    })
                }
                
                timer?.resume()
                
                
            } else {
                refreshTime()
            }
        }
    }
    
//    // MARK - 服务器返回当前时间和活动结束时间
//    open func updateTime(_ currentTime:String ,_ endTime:String) {
//
//    }
    
    // MARK - init
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }
    
    fileprivate func setUpUI() {
        addSubview(hourLbl)
        addSubview(hourDotLbl)
        addSubview(minuteLbl)
        addSubview(minuteDotLbl)
        addSubview(secondLbl)
        
        self.lableColor = UIColor.white
        self.lableTextColor = UIColor.brown
    }
    convenience init(frame: CGRect ,isStartTimer:Bool = true) {
        self.init(frame: frame)
        self.isStartTimer = isStartTimer
    }
    
    open var lableColor:UIColor? {
        didSet {
            guard let labelColor = lableColor else { return }
            hourLbl.backgroundColor   = lableColor
            minuteLbl.backgroundColor = labelColor
            secondLbl.backgroundColor = labelColor
        }
    }
    
    open var lableTextColor:UIColor? {
        didSet {
            guard let textColor = lableTextColor else { return }
            hourLbl.textColor = textColor
            minuteLbl.textColor = textColor
            secondLbl.textColor = textColor
        }
    }
    
    @objc func refreshTime() {
        guard let endTime = endTime else { return }
        //当前时间
        let nowDate = Date.getCurrentDate()
        //结束时间
        let endDate = endTime.timeStampToDate()
        
        let calendar = NSCalendar.current
        
        let compenents = calendar.dateComponents([.hour,.minute,.second], from: nowDate, to: endDate)
        
        guard let hour = compenents.hour,
              let minute = compenents.minute,
            let second = compenents.second else { return }
        
        if hour < 0 || minute < 0 || second < 0 {
            removeTimer();
            hourLbl.text = "00"
            minuteLbl.text = "00"
            secondLbl.text = "00"
        } else {
            hourLbl.text = "\(hour.keepInt())"
            minuteLbl.text = "\(minute.keepInt())"
            secondLbl.text = "\(second.keepInt())"
        }
    }
    
    // MARK - setUpUI
    // MARK - 小时
    fileprivate lazy var hourLbl:UILabel = {
        let hourL = UILabel()
        hourL.textAlignment = .center
        return hourL
    }()
    
    // MARK - 小时 后面的冒号
    fileprivate lazy var hourDotLbl:UILabel = {
        let hourDotL = UILabel()
        hourDotL.textAlignment = .center
        hourDotL.text = ":"
        return hourDotL
    }()
    
    // MARK - 分钟
    fileprivate lazy var minuteLbl:UILabel = {
        let minuteL = UILabel()
        minuteL.textAlignment = .center
        return minuteL
    }()
    
    // MARK - 分钟后面的冒号
    fileprivate lazy var minuteDotLbl:UILabel = {
        let minuteDotL = UILabel()
        minuteDotL.textAlignment = .center
        minuteDotL.text = ":"
        return minuteDotL
    }()
    
    // MARK - 秒
    fileprivate lazy var secondLbl:UILabel = {
        let secondL = UILabel()
        secondL.textAlignment = .center
        return secondL
    }()
  
    
    fileprivate func removeTimer() {
        if timer != nil {
            timer?.cancel()
            timer = nil
        }
    }
    
  
    deinit {
        removeTimer()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder aDecoder: NSCoder) has not been implement")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let textW = self.height
        let dotW = (self.width - (textW * 3))*0.5
        
        hourLbl.frame = CGRect(x: 0, y: 0, width: textW, height: textW)
        hourDotLbl.frame = CGRect(x: hourLbl.maxX, y: 0, width: dotW, height: textW)
        minuteLbl.frame = CGRect(x: hourDotLbl.maxX, y: 0, width: textW, height: textW)
        minuteDotLbl.frame = CGRect(x: minuteLbl.maxX, y: 0, width: dotW, height: textW)
        secondLbl.frame = CGRect(x: minuteDotLbl.maxX, y: 0, width: textW, height: textW)
        
        
    }
}
